<template>
  <div class="container">
    <CalcGridTemplate :btns="btns" @gridClick="onClick">
      <template #input>
        <div>{{ calcOptions.text }}</div>
      </template>

      <template #content>
        <div v-html="content"></div>
      </template>
    </CalcGridTemplate>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import relationship, { relationshipJsOption } from "relationship.js";

const TYPE_ENUM = {
  CLEAR: "CLEAR",
  BKSP: "BKSP",
  REVERSE: "REVERSE",
  CALC: "CALC"
};

const btns = reactive<GridType[]>([
  { type: "的丈夫", html: "夫" },
  { type: "的妻子", html: "妻" },
  {
    html: "C",
    type: TYPE_ENUM.CLEAR,
    attrs: {
      style: { color: "#e95804", fontSize: "24px" }
    }
  },
  {
    type: TYPE_ENUM.BKSP,
    attrs: {
      style: { color: "#e95804", fontSize: "32px" },
      class: "iconfont icon-backspace"
    }
  },
  { type: "的爸爸", html: "父" },
  { type: "的妈妈", html: "母" },
  { type: "的儿子", html: "子" },
  { type: "的女儿", html: "女" },
  { type: "的哥哥", html: "兄" },
  { type: "的弟弟", html: "弟" },
  { type: "的姐姐", html: "姐" },
  { type: "的妹妹", html: "妹" },
  { type: TYPE_ENUM.REVERSE, html: "互查", attrs: { class: "grid-span-3" } },
  {
    type: TYPE_ENUM.CALC,
    html: "=",
    attrs: {
      style: { fontSize: "38px", backgroundColor: "#e95804", color: "white" }
    }
  }
]);

const calcOptions: relationshipJsOption = reactive({
  text: "我",
  reverse: false
});
const content = ref("");

const onClick = (item: GridType, i: number) => {
  switch (item.type) {
    case TYPE_ENUM.CLEAR:
      clear();
      break;
    case TYPE_ENUM.BKSP:
      bksp();
      break;
    case TYPE_ENUM.REVERSE:
      reverse();
      break;
    case TYPE_ENUM.CALC:
      calc();
      break;
    default:
      calcOptions.text += item.type;
      break;
  }
};

const clear = () => {
  if (calcOptions.text.length === 1) return;
  calcOptions.text = "我";
  content.value = "";
};

const bksp = () => {
  if (calcOptions.text.length === 1) return;
  calcOptions.text = calcOptions.text.slice(0, -3);
};

const reverse = () => {
  if (calcOptions.text.length === 1) return;
  calcOptions.reverse = !calcOptions.reverse;
  calcOptions.sex = 1;
  calc();
};

const calc = () => {
  if (calcOptions.text.length === 1) return;
  const res = relationship(calcOptions);

  if (!res.length) {
    content.value = `<p style="color: red">无法计算!</p>`;
  } else if (res.length === 1) {
    content.value = res[0];
  } else {
    content.value = res.map((e, i) => `${i + 1}. ${e}<br />`).join("");
  }
};
</script>
